package com.woosiyuan.atie.demo;

import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.BitmapDrawable;
import android.media.MediaRecorder;
import android.os.Bundle;
import android.util.Log;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.PopupWindow;
import android.widget.ScrollView;
import android.widget.TextView;

import com.woosiyuan.atierobot.ArmStateListener;
import com.woosiyuan.atierobot.DriverManager;
import com.woosiyuan.atierobot.InfraredListener;
import com.woosiyuan.atierobot.LightStateListener;
import com.woosiyuan.atierobot.utils.AppInfo;
import com.woosiyuan.atierobot.utils.BaseActivity;
import com.woosiyuan.atierobot.utils.RobotBatteryUtils;
import com.woosiyuan.atierobot.utils.SoundUtil;
import com.woosiyuan.wsyrobotdemo.R;

import java.io.File;
import java.io.IOException;


public class MainActivity extends BaseActivity implements View.OnClickListener {
    private Activity activity;

    byte   ledColor = 1;
    byte[] data1    = new byte[1];

    private       Button             battery;
    private       DriverManager      manager;
    private       ScrollView         layout;
    private       TextView           battery_tv;
    private       MainActionReceiver receiver;
    public static InfraredListener   mInfraredListener;
    public static ArmStateListener   mArmStateListener;
    public static LightStateListener mLightStateListener;
    private String musicPath = "/sdcard/Dance/htys.mp3";
    private String recordPath = "/sdcard/Record/";


    @Override protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        activity = this;
        AppInfo.init(getApplicationContext());
        manager = DriverManager.getInstance();
        manager.init(this);
        battery = (Button) findViewById(R.id.battery);
        battery_tv = (TextView) findViewById(R.id.battery_tv);
//		Date date = new Date();
//		String s = date.toLocaleString();
//		String[] split = s.split(" ");
//		battery_tv.setText(split[0]);
		layout = (ScrollView) findViewById(R.id.main_layout);
        receiver = new MainActionReceiver();
        eventObstacleAvoid();
    }

    MediaRecorder mediaRecorder;
    public void doRecordVoice(String path){
        mediaRecorder = new MediaRecorder();
        // 第1步：设置音频来源（MIC表示麦克风）
        mediaRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
        /* 设置输出文件的格式：THREE_GPP/MPEG-4/RAW_AMR/Default THREE_GPP(3gp格式，H263视频/ARM音频编码)
         * 、MPEG-4、RAW_AMR(只支持音频且音频编码要求为AMR_NB)
         */
        //第2步：设置音频输出格式（默认的输出格式）
        mediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.AMR_NB);
         /* 设置音频文件的编码：AAC/AMR_NB/AMR_MB/Default */
        //第3步：设置音频编码方式（默认的编码方式）
        mediaRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
        //创建一个临时的音频输出文件
        //File audioFile = null;
        try {
            //audioFile = File.createTempFile("record_", ".amr");
            File tmp = new File(path);
            if(!tmp.exists()){
                tmp.mkdirs();
            }
            //第4步：指定音频输出文件
            mediaRecorder.setOutputFile(path+"record.amr");
            //第5步：调用prepare方法
            mediaRecorder.prepare();
            //第6步：调用start方法开始录音
            mediaRecorder.start();
            showMsg("开始录音");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    public void stopVideoRecording(){
        mediaRecorder.stop();
        showMsg("停止录音");
    }

    public void eventObstacleAvoid(){
        mInfraredListener = new InfraredListener() {
            @Override public void getMsg(int type) {
                switch (type) {
                    case 1:
                        showMsg("redbz 前置红外生效");
                        break;
                    case 2:
                        showMsg("redbz 后置红外生效");
                        break;
                    case 3:
                        showMsg("redbz 左边红外生效");
                        break;
                    case 4:
                        showMsg("redbz 右边红外生效");
                        break;
                }
            }
        };
    }

    public void doGetArmStatus(){//手臂
        mArmStateListener = new ArmStateListener() {
            @Override public void getState(boolean state) {
                showMsg("手臂isUp"+state);
            }
        };
    }
    public void doGetStatusLight(){//触角
        mLightStateListener = new LightStateListener() {
            @Override public void getState(boolean state) {
                showMsg("触角isOpen"+state);
            }
        };
    }
    public void doGetJackLight(){//照明
        mLightStateListener = new LightStateListener() {
            @Override public void getState(boolean state) {
                showMsg("照明isOpen"+state);
            }
        };
    }

    @Override protected void onDestroy() {
        super.onDestroy();
    }

    @Override public void onClick(View v) {
        switch (v.getId()) {
            // 自动行进
            case R.id.forwarda:
                manager.moveForwardAuto();
                break;
            case R.id.backwarda:
                manager.moveBackwardAuto();
                break;
            case R.id.lefta:
                manager.moveLeftAuto();
                break;
            case R.id.righta:
                manager.moveRightAuto();
                break;
            case R.id.movestop:
                manager.moveStop();
                break;
            // 头部控制
            case R.id.headUp:
                manager.headerUpAll();
                break;
            case R.id.headDown:
                manager.headerDownAll();
                break;
            case R.id.headStop:
                manager.headerStop();
                break;
            case R.id.headReset:
                manager.headerReset();
                break;
            // 左胳膊控制
            case R.id.leftArmUp:
                manager.leftArmUp();
                break;
            case R.id.leftArmDown:
                manager.leftArmDown();
                break;
            case R.id.leftArmStop:
                manager.leftArmStop();
                break;
            case R.id.leftArmReset:
                manager.leftArmReset();
                break;
            // 右胳膊控制
            case R.id.rightArmUp:
                manager.rightArmUp();
                break;
            case R.id.rightArmDown:
                manager.rightArmDown();
                break;
            case R.id.rightArmStop:
                manager.rightArmStop();
                break;
            case R.id.rightArmReset:
                manager.rightArmReset();
                break;
            // 灯光控制
            case R.id.ledopen:
                data1[0] = ledColor;
                manager.ledOpen(data1);
                ledColor += 1;
                if (ledColor > 7) {
                    ledColor = 1;
                }
                break;
            case R.id.ledclose:
                manager.ledClose();
                break;
            case R.id.lightopen:
                manager.lampSwitch(true);
                break;
            case R.id.lightclose:
                manager.lampSwitch(false);
                break;
            case R.id.ledopen1:
                data1[0] = (byte) 1;
                manager.ledOpen(data1);
                break;
            case R.id.ledopen2:
                data1[0] = (byte) 2;
                manager.ledOpen(data1);
                break;
            case R.id.ledopen3:
                data1[0] = (byte) 3;
                manager.ledOpen(data1);
                break;
            case R.id.ledopen4:
                data1[0] = (byte) 4;
                manager.ledOpen(data1);
                break;
            case R.id.ledopen5:
                data1[0] = (byte) 5;
                manager.ledOpen(data1);
                break;
            case R.id.ledopen6:
                data1[0] = (byte) 6;
                manager.ledOpen(data1);
                break;
            case R.id.ledopen7:
                data1[0] = (byte) 7;
                manager.ledOpen(data1);
                break;
            case R.id.cameratest:
                startActivity(new Intent(MainActivity.this, CameraActivity.class));
                break;
            case R.id.launcherbtn: {
                Intent intent = new Intent();
                intent.setComponent(new ComponentName("com.android.launcher",
                        "com.android.launcher2.Launcher"));
                intent.setAction(Intent.ACTION_VIEW);
                startActivity(intent);
            }
            break;
            case R.id.battery:
                battery_tv.setText("剩余电量："+RobotBatteryUtils.getBatteryLevel()+"%");
                break;
            case R.id.sound:
                showVolumePopupWindow(layout);
                break;
            case R.id.rightArmSta:
                manager.doGetArmStatus("right");
                doGetArmStatus();
                break;
            case R.id.leftArmSta:
                manager.doGetArmStatus("left");
                doGetArmStatus();
                break;
            case R.id.lampSta:
                manager.doGetStatusLight();
                doGetStatusLight();
                break;
                case R.id.ledSta:
                manager.doGetJackLight();
                doGetJackLight();
                break;
            case R.id.playMusic:
                doPlayMusic(musicPath);
                break;
            case R.id.startRecord:
                doRecordVoice(recordPath);
                break;
            case R.id.stopRecord:
                stopVideoRecording();
                break;
            case R.id.startVideoRecord:
                startActivity(new Intent(MainActivity.this, RecordActivity.class));
                break;
            case R.id.unBindService:
                DriverManager.getInstance().unInit();
                break;
            default:
                break;
        }
    }

    private void doPlayMusic(String path) {
        SoundUtil.play(path);
    }

    @Override protected void onPause() {
        super.onPause();
        hideVolumePopupWindow();
    }
    /** 隐藏音量控制窗口 */
    protected void hideVolumePopupWindow() {
        if (null != volumePopupWindow && volumePopupWindow.isShowing()) {
            volumePopupWindow.dismiss();
        }
    }
    protected VolumePopupWindow volumePopupWindow;
    /** 显示音量控制窗口 */
    protected void showVolumePopupWindow(View parent) {
        if (null == volumePopupWindow) {
            View view = LayoutInflater.from(this).inflate(R.layout.volume_popup_window, null);
            volumePopupWindow = new VolumePopupWindow(this, view,
                    ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT, false);
            // 需要设置一下此参数，点击外边可消失
            volumePopupWindow.setBackgroundDrawable(new BitmapDrawable());
            //设置点击窗口外边窗口消失
            volumePopupWindow.setOutsideTouchable(true);
            // 设置此参数获得焦点，否则无法点击
            volumePopupWindow.setFocusable(true);
            volumePopupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
                @Override public void onDismiss() {
                    volumePopupWindow = null;
                }
            });
        }
        if (null != volumePopupWindow && !volumePopupWindow.isShowing()) {
            final int titleBarHeight = dp2px(this, 96);
            volumePopupWindow.showAtLocation(parent, Gravity.TOP, 0, titleBarHeight);
        }
    }
    public static int dp2px(Context context, float dpVal) {
        return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dpVal, context.getResources().getDisplayMetrics());
    }

    public static void wakeUp(){
        Log.e("wakeUp","唤醒成功");
    }
}
